package com.billdowney.security.handler;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Service;

import com.billdowney.dao.user.UserLoginInfoDao;
import com.billdowney.entity.user.UserLoginInfo;
import com.billdowney.security.SecurityConst;
import com.billdowney.service.impl.base.BaseServiceImpl;
import com.billdowney.service.interfaces.system.log.SystemLogService;
import com.billdowney.util.http.HttpIOUtil;
import com.billdowney.util.log.SystemLogHandleType;
import com.billdowney.util.request.RequestUtil;
import com.billdowney.util.return_type.ReturnData;

/**
 * security登录失败处理
 * 
 * @author 超级小富翁 - BillDowney
 * @date 2019年2月7日 下午12:02:27
 */
@Service
public class LoginFailHandler extends BaseServiceImpl<UserLoginInfoDao, UserLoginInfo, String>
		implements AuthenticationFailureHandler {

	@Autowired
	private SystemLogService systemLogService;

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		HttpIOUtil.outJsonData(response, new ReturnData(exception));
		exception.printStackTrace();
		StringBuffer logDesc = new StringBuffer("用户尝试登陆失败：" + exception.getMessage());
		logDesc.append("；" + SecurityConst.USERNAME_FIELD + ":" + request.getParameter(SecurityConst.USERNAME_FIELD));
		logDesc.append("；" + SecurityConst.PASSWORD_FIELD + ":" + request.getParameter(SecurityConst.PASSWORD_FIELD));
		systemLogService.save(logDesc.toString(), SystemLogHandleType.common, getClass(), RequestUtil.getIpAddr(request));
	}

	@Resource(type = UserLoginInfoDao.class)
	@Override
	public void setDao(UserLoginInfoDao userLoginInfoDao) {
		super.dao = userLoginInfoDao;
	}

}
